package com.piper.lock;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

import java.util.Collections;

/**
 * @author piper
 **/
public class JedisLock {

    /**
     * 加锁
     */
    public static boolean lock(Jedis jedis, String key, String value, int second) {
        String result = jedis.set(key, value, SetParams.setParams().nx().ex(second));
        if (!"OK".equals(result)) {
            return false;
        }
        return Watchdog.startWatchdog(jedis, key, value, second);
    }

    /**
     * 释放分布式锁
     */
    public static boolean unLock(Jedis jedis, String key, String value) {
        Object result = jedis.eval(
                "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                        "return redis.call('del', KEYS[1]); " +
                        "else return 0; " +
                        "end;",
                Collections.singletonList(key), Collections.singletonList(value));
        return Long.valueOf(1).equals(result);
    }

}
